import React, {PureComponent} from "react";
import {connect} from "react-redux";
import {query} from "./actions";
import FilterForm from "../../components/FilterForm";
import {DATE_FORMAT} from "../../lib/func";
import {getLastFilter, getPrincipal, saveLastFilter} from "../../lib/identity";

const LAST_FILTER = "log";


class Filter extends PureComponent {
    state = {};
    handleSearch = (values) => {
        const {dispatch, pageSize} = this.props;
        let fields = values;
        this.setState({...fields});
        if (fields.createTimeRange && fields.createTimeRange.length > 1) {
            fields.createTimeStart = fields.createTimeRange[0].format(DATE_FORMAT);
            fields.createTimeEnd = fields.createTimeRange[1].format(DATE_FORMAT);
        }
        delete fields.createTimeRange;
        saveLastFilter(LAST_FILTER, {...fields});
        dispatch(query({...fields, pageSize, userId: getPrincipal().id}));
    };

    render() {
        const {loading, users} = this.props;
        let fields = getLastFilter(LAST_FILTER);
        if (fields === null || fields === undefined) {
            fields = {};
        }
        const filterSchema = [
            {
                key: 'userName',
                field: 'userName',
                title: '操作人',
                type: 'listSelector',
                expandable: true,
                fieldOptions: {
                    initialValue: this.state.userName || fields.userName
                },
                controlProps: {
                    dataSource: users,
                    labelField: "nickName",
                    valueField: "nickName"
                }
            },
            {
                key: 'targetId',
                field: 'targetId',
                type: 'text',
                expandable: true,
                title: '目标参数',
                fieldOptions: {
                    initialValue: this.state.targetId || fields.targetId
                }
            }, {
                key: 'createTimeRange',
                field: 'createTimeRange',
                type: 'dateRangePicker',
                expandable: true,
                title: '创建日期',
                fieldOptions: {
                    initialValue: this.state.createTimeRange || fields.createTimeRange
                }
            }

        ];
        return (
            <FilterForm schema={filterSchema} callback={this.handleSearch} loading={loading}/>
        );
    }
}

const mapStateToProps = state => {
    return {
        ...state.log.list
    };
};

export default connect(mapStateToProps)(Filter);
